import java.util.*;

public class Solution {

    public static int solution(int n, int[] nums) {
        if (n < 3) {
            return Arrays.stream(nums).max().orElse(Integer.MIN_VALUE);
        }

        // 去重并排序（降序）
        Set<Integer> numSet = new HashSet<>();
        for (int num : nums) {
            numSet.add(num);
        }

        List<Integer> sortedList = new ArrayList<>(numSet);
        sortedList.sort(Collections.reverseOrder());

        if (sortedList.size() < 3) {
            return sortedList.get(0);
        }

        return sortedList.get(2);
    }

    public static void main(String[] args) {
        System.out.println(solution(3, new int[]{3, 2, 1}) == 1);
        System.out.println(solution(2, new int[]{1, 2}) == 2);
        System.out.println(solution(4, new int[]{2, 2, 3, 1}) == 1);
    }
}